// web_project_2025/WebProject/src/main/java/cjj/AdminRegisterServlet.java
package cjj;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/admin/register")
public class AdminRegisterServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 显示注册页面
        request.getRequestDispatcher("/cjj/admin_register.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");

        // 获取表单数据
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");

        // 服务器端验证
        if (!password.equals(confirmPassword)) {
            request.setAttribute("errorMessage", "两次输入的密码不一致");
            request.getRequestDispatcher("/cjj/admin_register.jsp").forward(request, response);
            return;
        }

        if (username == null || username.trim().isEmpty() ||
                email == null || email.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            request.setAttribute("errorMessage", "所有字段均为必填项");
            request.getRequestDispatcher("/cjj/admin_register.jsp").forward(request, response);
            return;
        }

        Connection conn = null;
        try {
            // 调试：打印类加载器信息
            System.out.println("Servlet ClassLoader: " + getClass().getClassLoader());

            // 调试：验证驱动文件是否存在（需替换为实际路径）
            java.io.File driverFile = new java.io.File(
                    request.getServletContext().getRealPath("/WEB-INF/lib/mysql-connector-java-8.0.21.jar")
            );
            System.out.println("驱动文件存在: " + driverFile.exists());

            // 尝试手动加载驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("驱动类加载成功！");

            // 建立数据库连接（添加时区参数）
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/webproject_2025?useSSL=false&serverTimezone=UTC",
                    "root",
                    "root");
            System.out.println("数据库连接成功！");

            // 检查用户名是否已存在
            String checkSql = "SELECT id FROM admin WHERE username = ?";
            try (PreparedStatement checkStmt = conn.prepareStatement(checkSql)) {
                checkStmt.setString(1, username);
                try (ResultSet rs = checkStmt.executeQuery()) {
                    if (rs.next()) {
                        request.setAttribute("errorMessage", "用户名已被注册");
                        request.getRequestDispatcher("/cjj/admin_register.jsp").forward(request, response);
                        return;
                    }
                }
            }

            // 检查邮箱是否已存在
            String checkEmailSql = "SELECT id FROM admin WHERE email = ?";
            try (PreparedStatement checkEmailStmt = conn.prepareStatement(checkEmailSql)) {
                checkEmailStmt.setString(1, email);
                try (ResultSet rs = checkEmailStmt.executeQuery()) {
                    if (rs.next()) {
                        request.setAttribute("errorMessage", "该邮箱已被注册");
                        request.getRequestDispatcher("/cjj/admin_register.jsp").forward(request, response);
                        return;
                    }
                }
            }

            // 插入新管理员记录（使用密码哈希）
            String hashedPassword = hashPassword(password);
            String insertSql = "INSERT INTO admin (username, password, email, created_at) VALUES (?, ?, ?, NOW())";
            try (PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {
                insertStmt.setString(1, username);
                insertStmt.setString(2, hashedPassword);
                insertStmt.setString(3, email);
                insertStmt.executeUpdate();
            }

            // 注册成功，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/cjj/admin_login.jsp?registerSuccess=true");

        } catch (ClassNotFoundException e) {
            System.err.println("驱动类未找到异常: " + e.getMessage());
            e.printStackTrace();

            // 额外调试：打印类路径
            System.err.println("当前类路径: " + System.getProperty("java.class.path"));

            request.setAttribute("errorMessage", "注册失败: 数据库驱动加载失败，请联系管理员");
            request.getRequestDispatcher("/cjj/admin_register.jsp").forward(request, response);
        } catch (SQLException e) {
            System.err.println("数据库操作异常: " + e.getMessage());
            e.printStackTrace();

            // 区分常见SQL错误
            if (e.getSQLState().startsWith("23")) { // 约束冲突
                request.setAttribute("errorMessage", "注册失败: 数据格式不符合要求");
            } else {
                request.setAttribute("errorMessage", "注册失败: 数据库连接异常，请稍后重试");
            }
            request.getRequestDispatcher("/cjj/admin_register.jsp").forward(request, response);
        } catch (Exception e) {
            System.err.println("未知异常: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("errorMessage", "注册失败: 系统内部错误，请联系管理员");
            request.getRequestDispatcher("/cjj/admin_register.jsp").forward(request, response);
        } finally {
            // 关闭数据库连接
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 密码哈希方法（实际项目中建议使用BCrypt等更安全的算法）
    private String hashPassword(String password) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(password.getBytes("UTF-8"));
            StringBuilder hexString = new StringBuilder();

            for (byte b : hash) {
                String hex = String.format("%02x", b);
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException("密码哈希失败", e);
        }
    }

}